'use strict';

const path = require('path');
const OSS = require('ali-oss');
// const OssUploadStream = require('aliyun-oss-upload-stream');

const prefix = 'http://pp-station.oss-cn-beijing.aliyuncs.com/';
const aliInfo = {
  // https://help.aliyun.com/document_detail/31837.html
  region: 'oss-cn-beijing',
  bucket: 'pp-station',
  accessKeyId: 'LTAI5tSSD8ox6gP6LPAoCW4F',
  accessKeySecret: 'fJyh1NcgGrezMkJBVX2nISG9eMATms',
};
const client = new OSS(aliInfo);
// const ossStream = OssUploadStream(client);

const Service = require('egg').Service;

class OssService extends Service {
  async uploadFile(folder, stream) {
    // 获取扩展名
    const extname = path.extname(stream.filename ? stream.filename : stream.path).toLowerCase();
    // 获取文件名
    const filename = Date.now() + '' + Number.parseInt(Math.random() * 10000) + extname;
    const result = await client.putStream(`${folder}/${filename}`, stream);
    return result.url;
  }

  // 删除一个文件
  async deleteFile(filelink) {
    const { ctx } = this;
    const filename = ctx.helper.getOssFilename(filelink, prefix);
    const result = await client.delete(filename);
    return result;
  }

  // 删除多个文件
  async deleteMulti(fileLinks) {
    // 填写需要删除的多个Object完整路径并设置返回模式为详细模式。Object完整路径中不能包含Bucket名称。
    // let result = await client.deleteMulti(['exampleobject-1', 'exampleobject-2', 'testfolder/sampleobject.txt']);
    // 填写需要删除的多个Object完整路径并设置返回模式为简单模式。Object完整路径中不能包含Bucket名称。
    const { ctx } = this;
    const fileNames = fileLinks.map(item => ctx.helper.getOssFilename(item, prefix));
    const result = await client.deleteMulti(fileNames, { quiet: true });
    return result;
  }
}

module.exports = OssService;

